<?php


namespace app\api\controller\mini;

use app\api\model\mini\MiniVideoCollect;
use app\api\model\mini\MiniVideoItem;
use app\api\model\mini\MiniVideoPlan;
use app\api\model\mini\MiniVideoRecord;
use app\Request;
use learn\services\UtilService as Util;
use app\api\model\mini\MiniVideo as vModel;
use app\api\model\mini\MiniVideoItem as iModel;
use app\api\model\mini\MiniVideoOrder;
use HuaweiCloud\SDK\Core\Auth\GlobalCredentials;
use HuaweiCloud\SDK\Core\Http\HttpConfig;
use HuaweiCloud\SDK\Core\Exceptions\ConnectionException;
use HuaweiCloud\SDK\Core\Exceptions\RequestTimeoutException;
use HuaweiCloud\SDK\Core\Exceptions\ServiceResponseException;
use HuaweiCloud\SDK\Iam\V3\IamClient;
use HuaweiCloud\SDK\Iam\V3\Model\ListPermanentAccessKeysRequest;
use Monolog\Logger;

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\exception\ValidateException;

/**
 * Class MiniVideo
 * @package app\api\controller\mini
 */
class MiniVideo
{
    /**
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(Request $request)
    {
        $where = Util::postMore([
            ['vid', '']
        ]);
        if ($where['vid'] == "") return app("json")->fail("视频ID为空！");
        $data = vModel::getVideoInfo($where['vid'], $request->uid());
        return $data ? app("json")->success($data) : app("json")->fail("获取失败");
    }

    /**
     * 获取视频链接
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function url(Request $request)
    {
        $where = Util::postMore([
            ['vid', ''],
            ['xid', '']
        ]);
        if ($where['vid'] == "") return app("json")->fail("视频ID为空！");
        if (!vModel::isAllow($request->uid(), $where['vid'], $where['xid'])) return app("json")->make("2001", "您不拥有该视频！");
        $url = vModel::getUrlByVid($where['vid'], $where['xid']);
        MiniVideoRecord::record($request->uid(), $where['vid'], $where['xid']);
        $curNum = $where['xid'] ? iModel::where("vid", $where['vid'])->where("xid", $where['xid'])->where("status", 1)->value("name") : 1;
        $skip_sec = MiniVideoPlan::where("uid", $request->uid())->where("vid", $where['vid'])->where("xid", $where['xid'])->value("sec") ?: MiniVideoItem::where("vid", $where['vid'])->where("xid", $where['xid'])->where("status", 1)->value("skip_sec") ?: vModel::where("vid", $where['vid'])->where("status", 1)->value("skip_sec");
        return $url ? app("json")->success(compact("url", "curNum", "skip_sec")) : app("json")->fail("获取失败");
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function pause(Request $request)
    {
        $where = Util::postMore([
            ['vid', ''],
            ['xid', ''],
            ['sec', 0],
            ['uid', $request->uid()]
        ]);
        if ($where['vid'] == "") return app("json")->fail("视频ID为空！");
        return MiniVideoPlan::pause($where['uid'], $where['vid'], $where['xid'], $where['sec']) ? app("json")->success("记录成功") : app("json")->fail("记录失败");
    }

    /**
     * 收藏
     * @param Request $request
     * @return bool|int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function collect(Request $request)
    {
        $where = Util::postMore([
            ['vid', '']
        ]);
        if ($where['vid'] == "") return app("json")->fail("视频ID为空！");
        return MiniVideoCollect::UnAndOncollect($request->uid(), $where['vid']) ? app("json")->success("操作成功") : app("json")->fail("操作失败");
    }

    /**
     * 浏览记录
     * @param Request $request
     * @return
     */
    public function record(Request $request)
    {
        $where = Util::postMore([
            ['page', 1],
            ['limit', 10],
        ]);
        return app("json")->success("ok", MiniVideoPlan::lst($request->uid(), $where));
    }

    /**
     * 收藏列表
     * @param Request $request
     * @return mixed
     */
    public function collect_index(Request $request)
    {
        $where = Util::postMore([
            ['page', 1],
            ['limit', 10],
        ]);
        return app("json")->success("ok", MiniVideoCollect::lst($request->uid(), $where));
    }

    /**
     * 视频列表
     * @param Request $request
     * @return mixed
     */
    public function lst(Request $request)
    {
        $where = Util::postMore([
            ['page', 1],
            ['limit', 10],
            ['title', ''],
            ['type', '']
        ]);
        return app("json")->success("ok", vModel::search($where));
    }

    public  function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }


    public function wei_list(Request $request)
    {
    
        $token = '24.9f84eb5f0342ca579d78830e5d032323.2592000.1684311506.282335-32503440';
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/form?access_token=' . $token;
        $bodys = array(
            'url' => 'https://cs.zhonghanyi.cn/uploads/attach/2023/04/20230417/c218d0210c21e38d5f0407476214a0aa.jpg'
        );
        $res = self::request_post($url, $bodys);
        $res = json_decode($res, true);
        $date=[];
        $e=0;
        $max= self::searchmax($res['forms_result'][0]['body'],'column');
        foreach ($res['forms_result'][0]['body'] as $k => $v) {
                    if($v['column']==$max){
                       
                        $date[$e][]=$v['words'];
                        $e+=1;
                    }else{
                   
                    $date[$e][]=$v['words'];
                    }
     
            }

            $list=$date[0];
            unset($date[0]);
            self::export($list,$date);
    }
    
    
    public function searchmax($arr, $field) // 最小值 只需要最后一个max函数  替换为 min函数即可
    {
        if (!is_array($arr) || !$field) { //判断是否是数组以及传过来的字段是否是空
            return false;
        }
        $temp = array();
        foreach ($arr as $key => $val) {
            $temp[] = $val[$field]; // 用一个空数组来承接字段
        }
        return max($temp);  // 用php自带函数 max 来返回该数组的最大值，一维数组可直接用max函数
    }
    
    
    /**
     * 导出excel表格
     * @param array $header 设置表头数据
     * @param array $data 生成的表格数据
     * @param bool $type 文件类型，true为Xlsx，false为Xls，默认为true
     * @param string $fileName 文件名，默认为数据
     */
    protected function export($header = [], $data = [], $type = true, $fileName = "数据")
    {
        // 实例化类
        $preadsheet = new Spreadsheet();
        // 创建sheet
        $sheet =$preadsheet->getActiveSheet();
        // 生成表头字母
        $letter = [];
        $n = 0;
        for ($i = 'A'; $i <= 'Z'; $i++) {
            if ($n<count($header)){
                $letter[] = $i;
            }else{
                break;
            }
            $n++;
        }
        // 循环设置表头数据
        foreach ($header as $k => $v) {
            // 解决长数字自动转科学计数法
            if(is_numeric($v) && strlen($v) > 11){
                $sheet->setCellValueExplicit($letter[$k].'1',$v,'s');
            }

            $sheet->setCellValue($letter[$k].'1', $v);
        }
        // 生成数据
        $sheet->fromArray($data, null, "A2");
        // 样式设置
        $sheet->getDefaultColumnDimension()->setWidth(12);
        // 设置下载与后缀
        if ($type) {
            header("Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            $type = "Xlsx";
            $suffix = "xlsx";
        } else {
            header("Content-Type:application/vnd.ms-excel");
            $type = "Xls";
            $suffix = "xls";
        }
        // 激活浏览器窗口
        header("Content-Disposition:attachment;filename=$fileName.$suffix");
        //缓存控制
        header("Cache-Control:max-age=0");
        // 调用方法执行下载
        $writer = IOFactory::createWriter($preadsheet, $type);
        // 数据流
        $writer->save("php://output");
    }
}
